const match = require('@unblockneteasemusic/server');

// 带重试的匹配函数
async function matchWithRetry(id, providers, maxRetries = 1) {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      console.log(`Attempt ${attempt} for id ${id}`)
      const result = await match(id, providers)
      console.log('result',result)
      return result
    } catch (error) {
      console.error('error',error)
      if (attempt === maxRetries) throw error
      
      // 如果是JSON解析错误，等待后重试
      if (error.message?.includes('Unexpected token') && error.message?.includes('JSON')) {
        console.log(`JSON parse error on attempt ${attempt}, retrying...`)
        await new Promise(resolve => setTimeout(resolve, 1000 * attempt)) // 指数退避
        continue
      }
      
      throw error
    }
  }
}

const providers = ['migu', 'kugou', 'pyncmd']
const providersNo = ['migu', 'kugou',  'kuwo', 'pyncmd']

// 将 rawHeaders 数组转换为对象
function formatHeaders(rawHeaders) {
  const headers = {}
  for (let i = 0; i < rawHeaders.length; i += 2) {
    headers[rawHeaders[i]] = rawHeaders[i + 1]
  }
  return headers
}

// 判断是否使用 providersNo
function shouldUseProvidersNo(headers) {
  const referer = headers['Referer'] || headers['referer']
  const origin = headers['Origin'] || headers['origin']
  console.log('referer',referer)
  console.log('origin',origin)
  
  return referer === 'http://localhost/' || origin === 'http://localhost'
}

// 验证请求来源是否合法
function isValidOrigin(headers) {
  const referer = headers['Referer'] || headers['referer']
  const origin = headers['Origin'] || headers['origin']
  
  const validOrigins = [
    'http://localhost/',
    'http://localhost',
    'http://music.alger.fun',
    'http://music.alger.fun/',
    'https://music.alger.fun',
    'https://music.alger.fun/',
    'http://mc.alger.fun',
    'http://mc.alger.fun/',
    'https://mc.alger.fun',
    'https://mc.alger.fun/'
  ]
  
  // 至少有一个来源匹配
  const refererValid = !referer || validOrigins.some(valid => referer.startsWith(valid))
  const originValid = !origin || validOrigins.some(valid => origin === valid || origin === valid.replace(/\/$/, ''))
  
  return refererValid && originValid
}

exports.music = async (req, res) => {
  const headers = formatHeaders(req.rawHeaders)
  console.log('Formatted headers:', headers)
  
  // 验证请求来源
  if (!isValidOrigin(headers)) {
    console.warn('Forbidden: Invalid origin')
    return res.status(403).json({
      success: false,
      error: 'Forbidden: Invalid origin'
    })
  }
  
  try {
    let id = req.query.id
    
    if (!id) {
      return res.status(400).json({
        error: 'ID parameter is required'
      })
    }
    
    const numericId = parseInt(id)
    if (isNaN(numericId)) {
      return res.status(400).json({
        error: 'ID must be a valid number'
      })
    }
    
    // 根据 headers 决定使用哪个 providers
    const selectedProviders = shouldUseProvidersNo(headers) ? providersNo : providers
    console.log('Using providers:', selectedProviders)
    
    // 使用带重试的版本
    const data = await matchWithRetry(numericId, selectedProviders)
    
    res.json({
      success: true,
      data: data,
    })
  } catch (error) {
    const errorMessage = error?.message || 'Unknown error'
    
    console.error('Final error:', errorMessage)
    
    res.status(500).json({
      success: false,
      error: 'Music service unavailable',
      details: 'Please try again later or use a different music ID'
    })
  }
}